package br.ufmg.ubicomp.communication;

import java.util.ArrayList;
import java.util.Collection;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

import br.ufmg.ubicomp.utils.EntityProperties;
import br.ufmg.ubicomp.utils.StringUtils;

public class DroidServiceParamCommService extends CommunicationService{

	public Collection<EntityProperties> getServiceList() throws Exception
	{
		String url = getServerUrl()+"service/process?operation=list";
		Collection<EntityProperties> services = new ArrayList<EntityProperties>();		

		NodeList list = processRequest(url);
		
		for (int i = 0; i < list.getLength(); i++) {
			Node entityEntry = list.item(i);
			EntityProperties entity = null;
			if (entityEntry instanceof Element) {
				Element entityElement = (Element) entityEntry;
				entity = getEntityElement(entityEntry);
				
			}
			services.add(entity);
		}
		return services;			
	}
	
	public EntityProperties getService(String serviceKey, String droidGuideUserKey) throws Exception
	{
		String url = getServerUrl()+"service/process?operation=getService&"+
		"service_key="+serviceKey;
		if (!StringUtils.isEmpty(droidGuideUserKey))
		{
			url = url + "&droidGuideUser_key=" + droidGuideUserKey;
		}

		NodeList list = processRequest(url);
		
		EntityProperties service = new EntityProperties();
		for (int i = 0; i < list.getLength(); i++) {
			Node entityEntry = list.item(i);
			
			if (entityEntry instanceof Element) {
				service = getEntityElement(entityEntry);
			}
		}
		return service;	
		
	}

	public EntityProperties saveServiceParameterValue(String serviceKey, String droidGuideUserKey, 
			String serviceParameterKey, String value) throws Exception
	{
		String url = getServerUrl()+"service/process?operation=saveServiceParamValue&"+
		"service_key="+serviceKey+"&service_param_key="+serviceParameterKey+"&droidGuideUser_key="+droidGuideUserKey+"&value="+value;
		
		NodeList list = processRequest(url);
		String key = null;
		EntityProperties entity = new EntityProperties();
		for (int i = 0; i < list.getLength(); i++) {
			Node entityEntry = list.item(i);
			
			if (entityEntry instanceof Element) {
				Element entityElement = (Element) entityEntry;
				entity = getEntityElement(entityEntry);
			}
		}
		return entity;
		
	}
	
	public EntityProperties saveServiceParamValue(String key, String value) throws Exception
	{
		String url = getServerUrl()+"service/process?operation=saveServiceParamValue&"+
		"key="+key+"&value="+value;
		NodeList list = processRequest(url);

		EntityProperties entity = new EntityProperties();
		for (int i = 0; i < list.getLength(); i++) {
			Node entityEntry = list.item(i);
			
			if (entityEntry instanceof Element) {
				entity = getEntityElement(entityEntry);
			}
		}
		return entity;		
	}

}